package cn.nju.zyy.hello;

import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import cn.nju.zyy.persistence.JPAUtil;

public class HelloWorld {

	public static void main(String[] args) {
		// First unit of work
		EntityManager em = JPAUtil.getEntityManagerFactory().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		
		Message message = new Message("Hello World");
		em.persist(message);
		
		tx.commit();
		em.close();
		
		listMessages();
		
		// Shutting down the application
		JPAUtil.shutdown();
	}
	
	public static void listMessages() {
		// Second unit of work
		EntityManager em = JPAUtil.getEntityManagerFactory().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		
		List messages = em.createQuery("select m from Message m order by m.text asc")
						.getResultList();
		
		System.out.println(messages.size() + " message(s) found: ");
		
		for (Iterator iter = messages.iterator(); iter.hasNext(); ) {
			Message loadedMsg = (Message) iter.next();
			System.out.println(loadedMsg.getText());
		}
		
		tx.commit();
		em.close();
	}

}
